package net.lovesrc.allin.jobs.backup;

import com.alibaba.fastjson.JSONObject;
import net.lovesrc.allin.biz.gt.GtService;
import net.lovesrc.allin.jobs.base.BaseJob;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;

import java.util.List;

//@Component
@Profile("live")
public class GtProfitJob extends BaseJob {

    @Autowired
    private GtService gtService;

    @Override
    public void runOnce() throws Exception {
        if (RandomUtils.nextInt(0, 100) == 10) {
            jdbcTemplate.update("update t_gt_account set nextSignInTime = signInTime + interval 1 day + interval rand() * 600 second " +
                    " where (nextSignInTime < date(now()) or nextSignInTime is null)");

            // 收益时间，在签到时间附近
            jdbcTemplate.update("update t_gt_account set nextProfitTime = nextSignInTime - interval rand() * 60 second where nextProfitTime < date(now()) or nextProfitTime is null");
        }
        List<JSONObject> profitRows = queryForRows(jdbcTemplate, "select * from t_gt_account " +
                " where idStatus = 'success' and nextProfitTime between date(now()) and now() " +
                " and (profitTime < date(now()) or profitTime is null) " +
                " order by nextProfitTime" +
                " limit 5");
        for (JSONObject row : profitRows) {
            gtService.profit(row.getString("mobile"));
        }

        List<JSONObject> signInRows = queryForRows(jdbcTemplate, "select * from t_gt_account " +
                " where idStatus = 'success' and nextSignInTime between date(now()) and now() " +
                " and (signInTime  < date(now()) or signInTime is null) " +
                " order by nextSignInTime" +
                " limit 5");
        for (JSONObject row : signInRows) {
            gtService.signIn(row.getString("mobile"));
        }

        List<JSONObject> syncUserInfoRows = queryForRows(jdbcTemplate, "select * from t_gt_account " +
                " where idStatus = 'success' and nextSignInTime between date(now()) and now() " +
                " and (syncUserInfoTime < date(now()) or syncUserInfoTime is null) " +
                " and signInTime < now() - interval 1 minute and profitTime < now() - interval 1 minute" +
                " and signInTime > date(now())" +
                " limit 5");
        for (JSONObject row : syncUserInfoRows) {
            gtService.syncUserInfo(row.getString("mobile"));
        }
    }

    @Override
    protected long intervalMilliseconds() {
        return 1000 * RandomUtils.nextInt(5, 20);
    }

}
